/**
 * Created by Administrator on 2018/10/8.
 */

+function ($) {
    var EVENT_KEY = '.select.true';
    var selectTreeId = 0;
    var ExtSelectTree = function (f, e) {
        this.$element = $(f);
        this.options = $.extend({}, ExtSelectTree.DEFAULTS, this.$element.data(), e);
        this.init()
    };
    ExtSelectTree.DEFAULTS = {
        windowPadding: 0,
        async: {
            enable: true,
            type: "get",
            url: ""
        },
        data: {
            key: {
                name: "title"
            }
        },
        callback: {}
    };
    ExtSelectTree.prototype.init = function () {
        var that = this, options = this.options,
            id = this.$element.attr('id');
        selectTreeId++;
        this.selectTreeId = 'bs-select-' + selectTreeId;
        this.sizeInfo = {};
        this.$newElement = this.createDropdown();
        this.$element
            .after(this.$newElement)
            .prependTo(this.$newElement);
        this.$button = this.$newElement.children('button');
        this.$menu = this.$newElement.children('.dropdown-menu');
        this.$menuInner = this.$menu.children('.inner')
        this.$tree = this.$menuInner.children('.ztree');
        this.$buttonInner = this.$button.find('.filter-option-inner-inner');
        if (typeof id !== 'undefined') {
            this.$button.attr('data-id', id);
            this.$tree.attr('id', "tree_" + id);
        }
        if (options.url) {
            options.async.url = options.url;
        }
        var beforeAsync = function (treeId, treeNode) {
            var zTree = $.fn.zTree.getZTreeObj(treeId), dataUrl = that.options.url;
            const reg = new RegExp('\\{(.+?)\}');

            if (reg.test(dataUrl)) {
                var result = dataUrl.match(/\{(.+?)\}/g);
                for (var i = 0; i < result.length; i++) {
                    var macthValue = reg.exec(result[i])
                    if (treeNode == undefined) {
                        dataUrl = dataUrl.replace(macthValue[0], '');
                    } else {
                        dataUrl = dataUrl.replace(macthValue[0], treeNode[macthValue[1]]);
                    }
                }
                zTree.setting.async.url = dataUrl;

            }
            return true
        }

        options.callback.beforeAsync = beforeAsync;

        var winPad = options.windowPadding;
        if (typeof winPad === 'number') {
            this.options.windowPadding = [winPad, winPad, winPad, winPad];
        }


        options.callback.onClick = this.selected;
        $.fn.zTree.init(this.$tree, options);
        this.setListener();
    }
    ExtSelectTree.prototype.selected = function (event, treeId, treeNode) {
        var zTree = $.fn.zTree.getZTreeObj(treeId), nodes = zTree.getSelectedNodes(),
            value = [], name = [];
        for (var i = 0, l = nodes.length; i < l; i++) {
            value.push(nodes[i].id);
            name.push(nodes[i].title)
        }
        //this.$element.val(v);
        $("#" + treeId).trigger("selected.treeNode", [value.toString(), name.toString()]);
    }

    ExtSelectTree.prototype.setListener = function () {
        var that = this,
            $document = $(document);

        $document.data('spaceSelect', false);

        this.$button.on('click', function (e) {
            that.setMenuSize();
            that.$menu.slideDown("fast");
        });

        this.$tree.on('selected.treeNode', function (e, value, name) {
            that.$menu.fadeOut("fast");
            that.$element.val(value);
            that.$buttonInner.text(name)
        });

        $("body").bind("mousedown", function (e) {

            if (!($(event.target).parents(".inner").length > 0)) {
                that.$menu.fadeOut("fast");
            }
        });


        $(window)
            .off('resize' + EVENT_KEY + '.' + this.selectTreeId + '.setMenuSize' + ' scroll' + EVENT_KEY + '.' + this.selectTreeId + '.setMenuSize')
            .on('resize' + EVENT_KEY + '.' + this.selectTreeId + '.setMenuSize' + ' scroll' + EVENT_KEY + '.' + this.selectTreeId + '.setMenuSize', function () {
                return that.setMenuSize();
            });
    }

    ExtSelectTree.prototype.getSelectPosition = function () {
        var that = this,
            $window = $(window),
            pos = that.$newElement.offset();

        this.sizeInfo.selectOffsetTop = pos.top - $window.scrollTop();
        this.sizeInfo.selectOffsetBot = $window.height() - this.sizeInfo.selectOffsetTop - 280;

    },
        ExtSelectTree.prototype.setMenuSize = function () {
            this.getSelectPosition();

            var isDropup;

            isDropup = this.sizeInfo.selectOffsetTop - this.sizeInfo.selectOffsetBot > 30

            this.$newElement.toggleClass("open dropup", isDropup);
            if (isDropup) {
                this.$menuInner.height(this.sizeInfo.selectOffsetTop - 10)
            } else {
                this.$menuInner.height(280)
            }
        }

    ExtSelectTree.prototype.createDropdown = function () {
        var placeholder = this.$element.attr('placeholder');
        drop = '<div class="dropdown bootstrap-select show-tick form-control input-sm bs3" style="width: 100%;"> ' +
            '<button type="button" class="btn dropdown-toggle btn-default" role="combobox" aria-expanded="false"  >' +
            '<div class="filter-option"><div class="filter-option-inner">' +
            '<div class="filter-option-inner-inner">' + (placeholder !== 'undefined' ? placeholder : '请选择') + '</div>' +
            '</div>' +
            '</div>' +
            '<span class="bs-caret"><span class="caret"></span>' +
            '</button>' +
            '<div class="dropdown-menu">' +
            '<div class="inner " role="listbox"  tabindex="-1" style="overflow-y:auto;height:280px;">' +
            '<ul class="ztree" role="presentation" style="margin-top: 0px; margin-bottom: 0px;"></ul>' +
            '</div>' +
            '</div>'
        '</div>'

        return $(drop);
    }

    function Plugin(e) {
        Bolt.assert($.fn.zTree, "依赖组件 zTree 未引入");
        return this.each(function () {
            var h = $(this);
            var g = h.data("extSelectTree");
            var f = typeof e == "object" && e;
            if (!g) {
                h.data("extSelectTree", (g = new ExtSelectTree(this, f)))
            }
            if (typeof e == "string") {
                g[e]()
            }
        })
    }

    $.fn.extSelectTree = Plugin
    $.fn.extSelectTree.Constructor = ExtSelectTree;

    Bolt.addComponent({
        name: "ExtSelectTree",
        plugin: Plugin,
        runPoint: Bolt.eventType.afterAjaxPageShow,
        expr: "input[data-toggle='selectTree']",
        order: 800
    })
}(jQuery);